package com.fuda.trade.ui.orders

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.fuda.trade.databinding.FragmentOrdersBinding

class OrdersFragment : Fragment() {
    companion object {
        val TAG: String = OrdersFragment::class.java.simpleName
    }

    private lateinit var viewModel: OrdersViewModel
    private lateinit var swipeRefreshLayout: SwipeRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: OrdersAdapter


    private var _binding: FragmentOrdersBinding? = null

    // This property is only valid between onCreateView and onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this)[OrdersViewModel::class.java]

        _binding = FragmentOrdersBinding.inflate(inflater, container, false)
        val root: View = binding.root

        recyclerView = binding.recyclerOrders
        swipeRefreshLayout =binding.swipeRefreshLayout

        recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

        // Set up the SwipeRefreshLayout
        swipeRefreshLayout.setOnRefreshListener {
            viewModel.refreshData()
        }

        adapter = OrdersAdapter()
        recyclerView.adapter = adapter
        viewModel.orders.observe(viewLifecycleOwner, Observer { orders ->
            adapter.submitList(orders)
            // Request focus on the first item
            requestFocusOnFirstItem()
            swipeRefreshLayout.isRefreshing = false
        })
        return root
    }

    private fun requestFocusOnFirstItem() {
        recyclerView.postDelayed({
            // Smoothly scroll to the first position
            recyclerView.smoothScrollToPosition(0)

            // Wait for the scrolling to complete and request focus on the first visible item
            val layoutManager = recyclerView.layoutManager as LinearLayoutManager
            val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

            // Request focus on the first visible item
            if (firstVisibleItemPosition >= 0) {
                val firstVisibleItemView = recyclerView.findViewHolderForAdapterPosition(firstVisibleItemPosition)?.itemView
                firstVisibleItemView?.requestFocus()
            }
        }, 100) // Delay the focus request slightly to ensure the scrolling has completed
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private val scrollListener = object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)

            if (recyclerView.computeVerticalScrollOffset() == 0) {
                Log.d(TAG, "Trigger a refresh request")
                viewModel.refreshData()
            }
        }
    }
}